<template>
	<view>
		<view class="content">
			<scroll-view class="msg-list" scroll-y="true" show-scrollbar="false" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			 :refresher-enabled="refresherEnabled" :refresher-triggered="triggered" :refresher-threshold="50" @refresherpulling="pullingstart"	 @refresherrefresh="refreshStart"
			 @refresherrestore="refresherrestore" @refresherabort="refresherabort" :scroll-into-view="scrollToView">
				<view class="person-btn" v-if="!person" @tap="personEnter"><text>尊敬的客户，欢迎使用东莞证券在线客服，如您需要转接人工客服，请点击（转人工服务）</text></view>
					<view class="queue-msg" v-if="queueNum > 0"><text>您好，您前面还有<text class="queue-num">{{queueNum}}</text>人在排队，请您耐心等候，也可以通过95328电话联系客服哦。</text></view> 
				<view class="pull-tip" v-if="serviceInter && pullTip"><text>下拉获取历史记录</text></view>
				<view v-if="msgList.length">
					<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.msg.id">
						<!-- 系统消息 -->
						<block v-if="row.type=='system'">
							<view class="system">
								<!-- 文字消息 -->
								<view v-if="row.msg.type=='text'" class="text">
									{{row.msg.content.text}}
								</view>
							</view>
						</block>
						<!-- 工具连接消息 -->
						<view v-if="row.type=='link'" >
							<view class="message-link" v-if="row.msg.type=='link'" @tap="linkForward(row.msg)">
								<!-- 文字消息 -->
								<view class="link-name"  >
									<text>{{row.msg.content.link.toolName}}</text>
								</view>
								<view class="link-btn" >
									<text >点击前往</text>
								</view>
							</view>
						</view>
						<!-- 用户消息 -->
						<block v-if="row.type=='user'">
							<!-- 自己发出的消息 -->
							<view class="my" v-if="row.msg.userinfo.uid == smartTalkerId">
								<!-- 左-消息 -->
								<view class="left">
									<!-- 文字消息 -->
									<view v-if="row.msg.type=='text'" class="bubble">
										<rich-text class="rich-text" :nodes="row.msg.content.text"></rich-text>
									</view>
									<!-- 图片消息 -->
									<view v-if="row.msg.type=='img'" class="bubble img" @tap="showPic(row.msg)">
										<image :src="row.msg.content.url" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"></image>
                                    </view>
								</view>
							</view>
							<!-- 别人发出的消息 -->
							<view class="other" v-if="row.msg.userinfo.uid != smartTalkerId">
								<!-- 右-用户名称-时间-消息 -->
								<view class="right">
									<!-- 		<view class="username">
										<view class="name">{{row.msg.userinfo.username}}</view>
										<view class="time">{{row.msg.time | timestamp}}</view>
									</view> -->
									<!-- 文字消息 -->
									<view v-if="row.msg.type=='text'" class="bubble">
										<rich-text class="rich-text" :nodes="row.msg.content.text"></rich-text>
									</view>
									<!-- 图片消息 -->
									<view v-if="row.msg.type=='img'" class="bubble img" @tap="showPic(row.msg)">
										<image :src="row.msg.content.url" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"></image>
									</view>
								</view>
							</view>
						</block>
					</view>
				</view>

			</scroll-view>
		</view>
		<!-- 底部输入栏 fixed定位 bottom 0 -->
		<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 配置按钮 -->
			<view class="config-wrap">
				<scroll-view class="input-config" scroll-x="true" scroll-left="0">
					<view class="config-item" @tap="onComment"><text class="item">服务评价</text></view>
					<view class="config-item" v-for="nav in navList" :key="nav.id" @tap="nvaLink(nav)"><text class="item">{{nav.toolName}}</text></view> 
				</scroll-view>
			</view>
			<view class="input-item">
				<view class="textbox">
					<view class="text-mode">
						<view class="box">
							<textarea auto-height="true"  autofocus="autofocus" v-model.trim="textMsg"  @keyup.enter="sendText" />
							</view>
					</view>
				</view>
				<view class="more"  :class="showSend?'hidden':''" @tap="chooseImage">
					<view class="icon tupian2"></view>
				</view>
				<!--  -->
				<view class="send" :class="showSend?'':'hidden'" @tap="sendText">
					<view class="btn">发送</view>
				</view>
			</view>
		</view>
		<!-- 服务评价弹框 -->
		<view class="comment" v-if="commentShow">
			<evaluate :commentInfo="commentInfo" @commentClose="commentClose"></evaluate>
		</view>
		<view class="comment" v-if="imgPreview">
			<preview :imageSrc="imageSrc" @onPreview="onPreview"></preview>
		</view>
		<!-- <wyb-loading title="上传中" loading-type="flower" ref="imgLoading"/> -->
	</view>
</template>
<script>
	import { record,oldRecord,stopRecord,recordFile,recordUrl } from '@/static/HM-chat/record.js'
    import {wsSend,messageBody,randomeId,deepClone,msgBody,recoderTimeformat,dataURLtoFile,browser} from '@/utils/index.js'
	import {canvasDataURL} from '@/utils/compress.js'
	import  mixin from './mixin.js'
	import {emojiList,onlineEmoji} from './model.js'
	import {queryChat,netUploadFile,queryTool} from '@/api/index.js'
    import evaluate from './component/evaluate.vue';
	import preview from './component/preview.vue'
	import wybLoading from '@/components/wyb-loading/wyb-loading.vue'
	export default {
		components:{
			evaluate,
			preview,
			wybLoading
		},
		mixins: [mixin],
		data() {
			return {
				idInput:false,
				//文字消息
				textMsg:'',
				//消息列表
				isHistoryLoading:false,
				scrollAnimation:false,
				scrollTop:0,
				scrollToView:'',
				viewid:'',
				msgList:[],
				msgImgList:[],
				showLoading:false,
				willStop:false,
				initPoint:{identifier:0,Y:0},
				recordTimer:null,
				recordLength:0,
				// 抽屉参数
				popupLayerClass:'',
				// more参数
				hideMore:true,
				//表情定义
				hideEmoji:true,
				emojiList,
				onlineEmoji,
				// 请求历史数据
				queryList:[],
				ID: null, // 用户标志码（token）,
				pageNum:1,
				pageSize:5,
				person:false,
				pullTip:true,
				refresherEnabled:false,  //开启自定义下拉（scorll-view）
				triggered: false,
			    _triggered: false,
				commentShow:false,
				hasComment:false,
				commentInfo:{
					meetingId:this.meetingId,
					waiter:this.waiterId,
					member:this.ID
				},
				showSend:false,
				userName:'',
				navList:[],
				imageData:'',
				imageSrc:'',
				imgPreview:false,
				
			};
		},
		onLoad(params) {
			let ticket = ''
			if(params.ticket === undefined || params.ticket === 'undefined' || params.ticket === null || params.ticket === 'null'){
				ticket = ''
			}else{
			    ticket = params.ticket
			}
		   window.sessionStorage.setItem('ticket', ticket);
			// 获取app的版本号
		   window.setAppVersion = function(version){
			    window.sessionStorage.setItem('version', version);
		   },
		  this.getToken()
		},
		 watch:{
			 textMsg(val){
				 if(val){
				 	this.showSend = true
				 }else{
				 	this.showSend = false
				 }
			 },
			 serviceInter(val){
				 this.refresherEnabled = val
			 }
		 },
		 mounted(){
			 this.getNavs()
			// this.getTicket()
			// window.addEventListener('beforeunload',()=>{
			// 	let params = {
			// 	 	contentType:'0x29',
			// 	 	content: '用户主动退出了页面'
			// 	 }
			// 	 if(this.socketTask && this.socketTask.close){
			// 		wsSend(this.socketTask,params)
			// 		this.socketTask.close() 
			// 		this.bigSocketTask.close()
			// 		this.clearTimer()
			// 	 }
			// })
		 },
		methods:{
			getToken() {
				// 进入页面获取token
				let token = '';
				window.getNewToken = (tk) => {
					token = tk;
					if (token != '' ) {
						 window.sessionStorage.setItem('token', token);
					}
				};
				window.setToken = (tk) => {
					token = tk;
					if (token != '' ) {
						 window.sessionStorage.setItem('token', token);
					}
				};
				if(browser.ios){
					window.app_init = ()=>{
						console.log('browser.ios',browser.ios)
						if (window.KDS_Native && window.KDS_Native.getNewLoginAuthToken) {
							window.KDS_Native.getNewLoginAuthToken(false, 'getNewToken');
						} else if (window.KDS_Native && window.KDS_Native.getTokenWxApiNew) {
							window.KDS_Native.getTokenWxApiNew(false, 'getNewToken');
						}
					}
				}else{
					if (window.KDS_Native && window.KDS_Native.getNewLoginAuthToken) {
						window.KDS_Native.getNewLoginAuthToken(false, 'getNewToken');
					} else if ( window.KDS_Native && window.KDS_Native.getTokenWxApiNew) {
						window.KDS_Native.getTokenWxApiNew(false, 'getNewToken');
					}
				}
			},
			getTicket() {
				let ticket = sessionStorage.getItem('ticket')
				// app内调用原生登录，
				let timer = setInterval(() => {
					if (!ticket) {
						if (window.KDS_Native && window.KDS_Native.getTradeAuth) {
							window.KDS_Native.getTradeAuth();
						}
					} else {
						clearInterval(timer);
					}
				}, 500);
				// 准备给app的回调函数，注册到全局window上
				window.setTradeAuth = (tick) => {
					ticket = tick || '';
					if (tick == 'undefined' || tick == 'null') {
						ticket = '';
					}
					if (ticket) {
						sessionStorage.setItem('ticket', ticket);
					     window.location.reload()
					}
				};
				window.getTradeAuthCallback = () => {
					this.authFlag = false;
				};
			},
			// 导航栏
			getNavs() {
			  const params = {
				pageSize: 1000,
				pageNum: 1,
				isShow: 1
			  };
			  queryTool(params)
				.then((res) => {
				  const {
					data: { records},
				  } = res;
				  this.navList = records.filter(item=>item.isShow == 1);
				})
				.catch((err) => {
				  uni.showToast({
				      title: '导航接口异常',
				      duration: 2000,
				  	 icon:'none'
				  });
				});
			},
			nvaLink(nav){
				window.KDS_Native.switchDeeplink(nav.toolUrl)
				// window.open(nav.toolUrl)
			},
			personEnter(){
				if(this.bigSocketTask && this.bigSocketTask.onOpen){
					return 
				}
				this.person = true
				this.creatBigMeeting() 
			},
			pullingstart(){
				 console.log('下拉开始')
			},
			refreshStart(){
				 console.log('刷新开始')
			   if (this._triggered) {
					return;
				}
				this._triggered = true;
				//界面下拉触发，triggered可能不是true，要设为true
				if (!this.triggered) {
					this.triggered = true;
				}
				this.loadHistory()		
			},
			refresherrestore(){//下拉复位
				this.triggered = false;
				this._triggered = false;
			},
			refresherabort(){ //下拉被终止
				this.triggered = false;
				this._triggered = false;
			},
	        commentClose(e){
				this.commentShow = false
				const {closeType,...arg} = e
				this.hasComment = closeType
				if(closeType){
					console.log('arg',arg)
					let msg = {text:arg}
					this.sendMsg(msg,'comment');
				}
			},
			linkForward(params){
				const {content:{link:{toolUrl}}} = params
				if(window.KDS_Native){
					window.KDS_Native.switchDeeplink(toolUrl)
				}else{
					window.open(toolUrl)
				}
			},
			// 接受消息(筛选处理)
			screenMsg(msg){
				//从长连接处转发给这个方法，进行筛选处理
				if(msg.type=='system'){
					// 系统消息
					switch (msg.msg.type){
						case 'text':
							this.addSystemTextMsg(msg);
							break;
					}
				}else if(msg.type=='user'){
					// 用户消息
					switch (msg.msg.type){
						case 'text':
							this.addTextMsg(msg);
							break;
						case 'voice':
							this.addVoiceMsg(msg);
							break;
						case 'img':
							this.addImgMsg(msg);
							break;
					}
				}else if(msg.type=='link'){
						 this.addLinkMsg(msg)
					}
				this.$nextTick(()=> {
					// 滚动到底
					this.scrollToView = 'msg'+msg.msg.id
				});
			},
			// 获取历史记录
			async getHistory() {
				if(!this.ID){
				   return 	
				}
				const [start,end] = recoderTimeformat(new Date())
				const params = {
					talker: this.ID,
					pageNum:this.pageNum,
					pageSize:this.pageSize,
					startTime: start,
					endTime: end,
				}
				await queryChat(params).then(res => {
				        const historyList = res.data.list
			            this.queryList = []
						this.pageSize += 15
						if(this.pageSize >= res.data.total){
							this.pageSize = res.data.total
						}
					    historyList.forEach((item) => {
							let params = {
								id:item.id,
								type:'user',
								uid: item.talker,
								time:item.serverTime
							}
							if(item.contentType === "0x41"){
								this.queryList.push(messageBody({...params,content:{text:item.content},talkType:'text'}))
							}
							if(item.contentType == "0x45"){
								this.queryList.push(messageBody({...params,content:{url:item.content},talkType:'img'}))
							}
							if(item.contentType == "0x42"){
								this.queryList.push(messageBody({...params,content:{url:item.content},talkType:'voice'}))
							}
							if(item.contentType == "0x62"){
								params.type = 'link'
								this.queryList.push(messageBody({...params,content:{link:JSON.parse(item.content)},talkType:'link'}))
							}
					    })
						// 消息列表
						let list = deepClone(this.queryList)
						this.msgList = []
						// 获取消息中的图片,并处理显示尺寸
						for(let i=0;i<list.length;i++){
							if(list[i].type=='user'&&list[i].msg.type=="img"){
								list[i].msg.content = this.setPicSize(list[i].msg.content);
								this.msgImgList.unshift(list[i].msg.content.url);
							}
							this.msgList.unshift(list[i]);
						}
						this.isHistoryLoading = false;//参数作为进入请求标识，防止重复请求
						//这段代码很重要，不然每次加载历史数据都会跳到顶部
						this.$nextTick(function() {
							this.scrollToView = 'msg'+ this.viewid;//跳转上次的第一行信息位置
							this.$nextTick(function() {
								this.scrollAnimation = true;//恢复滚动动画
							});
						});
				      }).catch(err => {
					    uni.showToast({
					        title: '历史查询接口异常',
					        duration: 2000,
					    	 icon:'none'
					    });
				      }).finally(()=>{
						this.pullTip = false
				})
			},
			
			//触发滑动到顶部(加载历史信息记录)
		   async loadHistory(){
				if(this.isHistoryLoading){
				   let timer = setTimeout(()=>{
						this.triggered = false
						this._triggered = false
						clearTimeout(timer)
					},300)
					return ;
				}
				this.isHistoryLoading = true;//参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false;//关闭滑动动画
				this.viewid = this.msgList[0] ? this.msgList[0].msg.id :'_9527';//记住第一个信息ID
				await this.getHistory() 
				this.triggered = false
				this._triggered = false
			},

			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content){
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350);//350是定义消息图片最大宽度
				let maxH = uni.upx2px(350);//350是定义消息图片最大高度
				if(content.w>maxW||content.h>maxH){
					let scale = content.w/content.h;
					content.w = scale>1?maxW:maxH*scale;
					content.h = scale>1?maxW/scale:maxH;
				}
				return content;
			},
			// 选择图片发送
			chooseImage(){
				if(!this.serviceInter){
					uni.showToast({
					    title: '暂未接入客服',
					    duration: 2000,
						  icon:'none'
					});
					return
				}
				window.setImg =  (img)=> {
				   if (typeof img === 'object') {
						img = img.imageData
					  }
				this.imageData = img
				this.imageSrc = 'data:image/jpeg;base64,' + img
				const file1 = dataURLtoFile(this.imageData,'fileName')
				 // console.log('压缩前',file1)
				 if(file1.size > 10000*1024){
					  uni.showToast({
					      title: '图片尺寸过大',
					      duration: 2000,
					  	  icon:'none'
					  });
					  return
				 }else{
					 this.imgPreview = true
				 }
				// this.imgUpload(img)
				}
			  this.getImage('album');
			},
			//拍照发送
			camera(){
				this.getImage('camera');
			},
			//选照片 or 拍照
			getImage(type){
				// this.hideDrawer();
				if(window.KDS_Native){
					// window.KDS_Native.startPhone()
					window.KDS_Native.startPhotoAlbum()
				}else{
				   uni.chooseImage({
				   	sourceType:['album'],//选照片 or 拍照
				   	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				   	success: (res)=>{
						this.imageSrc = res.tempFilePaths[0]
						this.imgPreview = true
				   		// for(let i=0;i<res.tempFilePaths.length;i++){
				   		// 	uni.getImageInfo({
				   		// 		src: res.tempFilePaths[i],
				   		// 		success: (image)=>{
				   		// 			let afterImgData = ''
				   		// 			canvasDataURL(res.tempFilePaths[i],{},(img)=>{
				   		// 				  afterImgData = img
				   		// 				  const file = dataURLtoFile(afterImgData.split(',')[1],'122.jpg')
				   		// 				  console.log('file',file)
				   		// 				  // 上传至服务器
				   		// 				  let data = {
				   		// 				  	meetingId: this.meetingId,
				   		// 				  	memberId: this.ID,
				   		// 				  	waiterId: this.waiterId,
				   		// 				  	contentType: 12,
				   		// 				  	content: ''
				   		// 				  }
				   		// 				  const params = JSON.stringify(msgBody(data))
				   		// 				 		uni.showLoading({
				   		// 				            title: '上传中'
				   		// 			           });
				   		// 				  netUploadFile(file,{body:params}).then((res)=>{
				   		// 				  	const {data} = res
				   		// 				  	let msg = {url:data,w:image.width,h:image.height};
				   		// 				  	this.sendMsg(msg,'img');
				   		// 					uni.hideLoading()
				   		// 				  }).catch(err=>{
				   		// 				  	uni.showToast({
				   		// 				  	    title: '上传失败！',
				   		// 				  	    duration: 2000,
				   		// 				  		icon: 'none',
				   		// 				  	});
				   		// 					uni.hideLoading()
				   		// 				  })
				   		// 			})
				   		// 		}
				   		// 	});
				   		// }
				   	},
				   	fail:(e)=>{
				   		uni.showToast({
				   		    title: '上传失败！',
				   		    duration: 2000,
				   			icon: 'none',
				   		});
				   		uni.hideLoading()
				   	},
				   });
				}
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus(){
				if(this.popupLayerClass=='showLayer' && this.hideMore == false){
					// this.hideDrawer();
				}
			},
			// 发送文字消息
			sendText(){
				if(!this.serviceInter){
					this.textMsg = '';//清空输入框
					uni.showToast({
					    title: '暂未接入客服',
					    duration: 2000,
						  icon:'none'
					});
					return
				}
				if(!this.textMsg){
					return;
				}
				// let content = this.replaceEmoji(this.textMsg);
				let content = this.textMsg.replace(/[\r\n]/g,"<br/>").replace(/\s/g,"&nbsp;")
				let msg = {text:content}
				this.sendMsg(msg,'text');
				this.textMsg = '';//清空输入框
			},
			// 发送消息
			sendMsg(content,type){	// type="text|img|voice|comment"
			   let contentType = ''
			   if (type === 'text') contentType = '0x40'
			   if (type === 'img') contentType = '0x44'
			   if (type === 'comment') contentType = '0x58'
				// 发送消息
				let params = {
					contentType,
					content: content.url || content.text 
				}
				if(this.wsOpen){
					wsSend(this.socketTask,params) //小会场
				}else{
				    wsSend(this.bigSocketTask,params)	//主会场
				}
			    },
			// 添加文字消息到列表
			addTextMsg(msg){
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg){
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg){
				msg.msg.content = this.setPicSize(msg.msg.content);
				this.msgImgList.push(msg.msg.content.url);
				this.msgList.push(msg);
			},
		
			addLinkMsg(msg){
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg){
				this.msgList.push(msg);
			},
			sendSystemMsg(content,type){
				let lastid = this.msgList[this.msgList.length-1].msg.id;
				lastid++;
				let row = {type:"system",msg:{id:lastid,type:type,content:content}};
				// this.screenMsg(row)
			},
			// 预览图片
			showPic(msg){
				console.log(';;')
				uni.previewImage({
					indicator:"none",
					current:msg.content.url,
					urls: this.msgImgList
				});
			},
			discard(){
				return;
			},
			onComment(){
				 if(!this.serviceInter){
					 uni.showToast({
					     title: '暂未接入客服',
					     duration: 2000,
					 	 icon:'none'
					 });
					 return
				 }
				 if(this.hasComment){
				 	uni.showToast({
				 	    title: '您已评价！',
				 	    duration: 2000,
						icon:'none'
				 	});
				 	return
				 }
				this.commentInfo = {
					meetingId:this.meetingId,
					waiter:this.waiterId,
					member:this.ID
				} 
				this.commentShow = true
			 },
			 onPreview(param){
				 this.imgPreview = false
			 	if(param){
			        canvasDataURL(this.imageSrc ,{quality:0.7},(afterImgData)=>{
						let img = afterImgData.split(',')[1]
				        this.imgUpload(img) 
			      })
			   }			 
			 },
			 imgUpload(imgData){
				uni.showLoading({
					title: '上传中'
				});
				 const file = dataURLtoFile(imgData,'fileName')
				 // console.log('压缩后',file)
				    let data = {
				    	meetingId: this.meetingId,
				    	memberId: this.ID,
				    	waiterId: this.waiterId,
				    	contentType: 12,
				    	content: ''
				    }
				    const params = JSON.stringify(msgBody(data))
				    netUploadFile(file,{body:params}).then((res)=>{
				    	 const { data } = res;
				    	let msg = {url:data[0].url};
				    	this.sendMsg(msg,'img');
						uni.hideLoading()
				    }).catch(err=>{
						uni.hideLoading()
				    	uni.showToast({
				    	    title: '上传失败！',
				    	    duration: 2000,
							icon: 'none',
				    	});
				    })
			 },
		
			 
			  // 继续
		}
	}
</script>
<style lang="scss">
	@import "@/static/HM-chat/css/style.scss"; 
	.rich-text{
		word-break: break-word;
	}
	.user-id{
		text-align: center;
		font-size: 24upx;
		color: blue;
	}
	.person-btn{
	   position: absolute;
	   top:20upx;
	   width: 100%;
	   font-size: 28upx;
	   color: #72819B;
	   padding:20upx;
	   background: #FFFFFF;
	   border: 0 solid #CCD3E5;
	   border-radius: 4px;
	   box-sizing: border-box;
	}
	.pull-tip{
		width: 100%;
		font-size: 24upx;
		text-align: center;
		padding-top:10upx;
		color:#72819B;
	}
	.comment{
		position: fixed;
		bottom: 2upx;
		z-index: 1000;
		width: 100%;
	}
	.queue-msg{
		position: absolute;
		top:40upx;
		background: rgba(126, 159, 246, 0.2);
		border-radius: 6px 6px 6px 0;
		color: #333333;
		max-width: 70%;
		min-height: 25px;
		padding: 10px;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		font-size: 14px;
		word-break: break-word;
		.queue-num{
			color: #7E9FF6;
			font-weight: 700;
		}
	}
</style>
